package com.feib.soeasy.security;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.util.RequestMatcher;

import com.feib.soeasy.model.User;
import com.feib.soeasy.model.UserActionLog;
import com.feib.soeasy.model.UserLoginControl;
import com.feib.soeasy.service.UserActionLogService;
import com.feib.soeasy.service.UserLoginControlService;
import com.feib.soeasy.service.UserService;

/**
 * @title (#)SoeasyAuthenticationSuccessHandlerImpl.java<br>
 * @description <br>
 * @author Anson Tsai<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/12/5 create by Anson Tsai<br>
 */
public class SoeasyAuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    private static final Logger logger = LoggerFactory.getLogger(SoeasyAuthenticationSuccessHandlerImpl.class);

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    private String targetUrl;
    
    /* eBIlling功能提升_第二階段, eBilling分由不同頁面登入 */
    @Resource(name="soeasyAuthenticationEntryPoint")
    private SoeasyDelegatingAuthenticationEntryPoint soeasyAuthenticationEntryPoint;

    @Autowired
    private UserLoginControlService userLoginControlService;

    @Autowired
    private UserActionLogService userActionLogService;
    
    @Autowired
    private UserService userService;
    
    /*
     * (non-Javdoc)
     * 
     * @see
     * org.springframework.security.web.authentication.AuthenticationSuccessHandler
     * #onAuthenticationSuccess(javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse,
     * org.springframework.security.core.Authentication)
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if (logger.isTraceEnabled()) {
            logger.trace("SoeasyAuthenticationSuccessHandlerImpl - start");
        }

        //儲存UserActionLog記錄
        UserActionLog log = new UserActionLog();
        log.setInDateTime(new Date());
        
        String groupNo = null;// 帳單業者統一編號
        String userId = null;// 使用者名稱
        UserLoginControl c = null;
        User user = null;
        if (null != authentication.getPrincipal() && authentication.getPrincipal() instanceof SoeasyUserDetails) {
            logger.trace("從 Spring Security principal 取得 User 物件，依據User物件取得 UserLoginControl 物件");
            user = ((SoeasyUserDetails) authentication.getPrincipal()).getUser();
        }
        else
        {
            logger.trace("從 Spring Security authentication 取得 帳號 與 業者代號，並依這兩個欄位取得 UserLoginControl 物件");
            /**
             * 使用者登入群組帳號
             */
            String name = authentication.getName();
            String[] userNameTemp = name.split("_conjunction_");
            groupNo = userNameTemp[0];// 帳單業者統一編號
            userId = userNameTemp[1];// 使用者名稱
            logger.trace("groupNo : " + groupNo);
            logger.trace("userId : " + userId);
            user = userService.loginByUerIdGroupNo(userId, groupNo);
        }
        
        // 更新使用者狀態
        user.setPwdErrorTime(new Integer(0));
        user.setCaptchaErrorTime(new Integer(0));
        user.setLastLogingDate(new Date());        
        userService.saveUser(user);
        
        groupNo = user.getGroup().getGroupNo();
        userId = user.getUserId();
        c = userLoginControlService.findByUer(user);                
        
        if (null == c) {
            c = new UserLoginControl();
            c.setActived(Boolean.FALSE);
            c.setUser(user);
        }
        
        UserDetails userDetails = (UserDetails)authentication.getPrincipal();        
        WebAuthenticationDetails detail = (WebAuthenticationDetails) authentication.getDetails();
        
        if (c.getActived())
        {
            SecurityContextHolder.clearContext();
            
            // Redirect to target page.
            /* eBIlling功能提升_第二階段, eBilling分由不同頁面登入 */
            //logger.trace("Redirect to errorUrl page : " + errorUrl + "?error=6");
            //redirectStrategy.sendRedirect(request, response, errorUrl + "?error=6");
            
            String errorUrl = null;
            if (null != groupNo)
            {
            	if ("000000000001".equals(groupNo))
            		errorUrl = "/admlogin.jsp";
            	else
            		errorUrl = "/login.jsp";
            }
            else
            {
            	LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints = soeasyAuthenticationEntryPoint.getEntryPoints();
                errorUrl = ((LoginUrlAuthenticationEntryPoint)soeasyAuthenticationEntryPoint.getDefaultEntryPoint()).getLoginFormUrl();
                for (RequestMatcher requestMatcher : entryPoints.keySet()) {
        			if (requestMatcher.matches(request))
        			{
        				LoginUrlAuthenticationEntryPoint ep = (LoginUrlAuthenticationEntryPoint)entryPoints.get(requestMatcher);
        				errorUrl = ep.getLoginFormUrl();
        			}
        		}
            }
            
            redirectStrategy.sendRedirect(request, response, errorUrl+ "?error=6");
            
            if (logger.isTraceEnabled()) {
                logger.trace("SoeasyAuthenticationSuccessHandlerImpl - end");
            }            
            return;
        }       
        
        // 更新使用者登入資料
        c.setSessionId(detail.getSessionId());
        c.setLoginTime(new Date());
        c.setLoginLocale(detail.getRemoteAddress());
        c.setActived(userDetails.isEnabled());
        c.setActivityTime(new Date());
        userLoginControlService.save(c);

        log.setGroupPk(user.getGroup().getGroupPk());
        log.setGroupNo(groupNo);
        log.setUserPk(user.getUserPk());
        log.setUserId(userId);
        log.setActionBean("LoginActionBean");
        log.setEventName("login");
        log.setRemoteAddr(detail.getRemoteAddress()); 
        log.setLogNote("登入成功");
        log.setOutDateTime(new Date());
        userActionLogService.addUserActionLog(log);
        
        // Redirect to target page.
        logger.trace("Redirect to targetUrl page : " + targetUrl);
        redirectStrategy.sendRedirect(request, response, targetUrl);

        if (logger.isTraceEnabled()) {
            logger.trace("SoeasyAuthenticationSuccessHandlerImpl - end");
        }
    }

    /**
     * @return 傳回 targetUrl。
     */
    public String getTargetUrl() {
        return targetUrl;
    }

    /**
     * @param targetUrl 要設定的 targetUrl。
     */
    public void setTargetUrl(String targetUrl) {
        this.targetUrl = targetUrl;
    }

}
